import { ReactElement, useEffect, useState  } from "react";
import React, { ChangeEvent, FC } from "react";
import Input , { inputProps } from '../Input/input';
import useDebounce from '../../hooks/useDebounce';


//如果要自定义加属性就继承DataSourceType
interface DataSourceObject {
    value: string ,
}

export type DataSourceType<T = {}> = T & DataSourceObject;

interface autoCompleteProps extends Omit<inputProps,'onSelect'> {
    //返回值必须为DataSourceObject类型的数组， 联合类型
    fetchSuggestions: (str:string) => DataSourceType[];
    onSelect?: (item: DataSourceType)=>void;
    renderOption?: (item:DataSourceType) => ReactElement; 
};

const AutoComplete:FC<autoCompleteProps> = (props)=>{

    const {
        fetchSuggestions,
        onSelect,
        value,
        renderOption,
        ...restProps
    } = props;

    const [inputValue , setInputValue] = useState(value as string);
    const [suggestions , setSuggestions] = useState<DataSourceType[]>([]);
    const [loading, setLoading] = useState(false);

    const debounceValue = useDebounce( inputValue ,500);


    useEffect( function () {
        if (debounceValue) {
            const arrStr = fetchSuggestions(debounceValue);      
            if (arrStr instanceof Promise) {
                setLoading(true);
                arrStr.then((data)=>{
                    setSuggestions(data);
                    setLoading(false);
                });
            } else {
                setSuggestions(arrStr)            
            } 
        }else {
            setSuggestions([]);
        }
    } , [debounceValue]);

    const handleChange = (e:ChangeEvent<HTMLInputElement>) => {
        const value = e.target.value.trim();
        setInputValue(value);
    };

    const handleSelect = (item:DataSourceType)=>{
        setInputValue(item.value);
        setSuggestions([]);
        if(onSelect) { 
            onSelect(item);
        }
    };

    const renderTemplate = (item:DataSourceType)=>{
        return renderOption ? renderOption(item) : item.value;
    }

    const generateDropdown = ()=>{
        return (<ul> 
            {suggestions.map((item, index)=>{
                return(<li onClick={()=>{ handleSelect(item) }} key={index}>{renderTemplate(item)}</li>)
           })}
        </ul>);
    };

    return <div>
        <Input
            value={inputValue}
            onChange={handleChange}
            {...restProps}
        />
        <div>
        {loading ? <ul>正在加载中</ul> : '' }
        {(suggestions.length > 0) ? generateDropdown() : ''}
        </div>
    </div>
};


export default AutoComplete;
